export function isValidUsername(str: string) {
  return ['admin', 'editor'].includes(str.trim())
}

export const isExternal = (path: string) => /^(https?:|mailto:|tel:)/.test(path)

export function isArray(arg: any) {
  if (typeof Array.isArray === 'undefined') {
    return Object.prototype.toString.call(arg) === '[object Array]'
  }
  return Array.isArray(arg)
}

export function isValidURL(url: string) {
  const reg = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d?)(\.(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:\d+)*(\/($|[\w.,?'\\+&%$#=~-]+))*$/
  return reg.test(url)
}
/** 大小写字母、汉字、下划线校验 */
export function validateName(name: string, minLen: number, maxLen: number) {
  const reg = new RegExp(`^[a-zA-Z0-9_\u4E00-\u9FA5]{${minLen},${maxLen}}$`)
  return reg.test(name)
}
/** 大小写字母、汉字校验 */
export function validateText(name: string, minLen: number, maxLen: number) {
  const reg = new RegExp(`^[a-zA-Z0-9\u4E00-\u9FA5]{${minLen},${maxLen}}$`)
  return reg.test(name)
}
/** 大小写字母、下划线校验 */
export function validateCode(code: string, minLen: number, maxLen: number) {
  const reg = new RegExp(`^[a-zA-Z0-9_]{${minLen},${maxLen}}$`)
  return reg.test(code)
}

/** 校验非空 */
export function validateEmpty(value: any) {
  // 检查值是否存在且不为空
  if (value === null || value === undefined || value === '') {
    return false
  }
  return true
}

// 正则校验
export function isValidRegExp(text: string) {
  try {
    /* eslint-disable no-new */
    new RegExp(text)
    return true
  }
  catch {
    return false
  }
}

// 是否存在交集、
export function intersectIntervals(intervals = []) {
  if (Array.isArray(intervals) && intervals.length === 0) {
    return null
  }
  if (intervals.length === 1) {
    return null
  }
  intervals.sort((a, b) => a[0] - b[0])
  let result = intervals[0]
  // 遍历每个区间，计算交集
  for (let i = 1; i < intervals.length; i++) {
    // 检查当前区间与结果区间的交集
    if (result[1] >= intervals[i][0]) { // 如果有交集
      result[0] = Math.max(result[0], intervals[i][0])// 更新交集的起始位置
      result[1] = Math.min(result[1], intervals[i][1])// 更新交集的结束位置
    }
    else {
      // 如果没有交集，则提前结束循环
      result = null
      break
    }
  }
  return result
}
